package cn.itsource.pethome.user.interceptor;

import cn.itsource.pethome.user.domain.LoginInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //获取token的值
        String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)){
//            提示前端用户，登录超时，请重新登录 (这里的token会一直有 因为前端用的localStorage存储)
            wirteError(response);
            return false;
        }
        LoginInfo loginInfo = (LoginInfo) redisTemplate.opsForValue().get(token);
        if(loginInfo == null){
            // 提示前端用户，登录超时，请重新登录
            wirteError(response);
            return false;
        }
        redisTemplate.opsForValue().set(token, loginInfo, 30, TimeUnit.MINUTES);
        return true;
    }


    private void wirteError(HttpServletResponse response){
        try {
            response.setContentType("text/json;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.write("{\"success\":false,\"msg\":\"noLogin\"}");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


}
